package com.insta.java.webservice;

import java.util.Date;
import java.util.List;
import javax.jws.WebService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.insta.java.dto.LocationDto;
import com.insta.java.dto.UserDto;
import com.insta.java.metier.LocationManager;
import com.insta.java.metier.UserManager;
import com.insta.java.model.Location;
import com.insta.java.model.User;
import com.insta.java.util.LocationConvert;
import com.insta.java.util.UserConvert;


@WebService(endpointInterface= "com.insta.java.webservice.IUserWSD")
public class UserService implements IUserWSD{
	
	private static LocationManager locationManager;
	private static UserManager	userManager;
	
	public UserService(){
		ApplicationContext appContext = new ClassPathXmlApplicationContext("spring/config/BeanLocations.xml");	
		
		userManager= (UserManager) appContext.getBean("userManager");
		locationManager= (LocationManager) appContext.getBean("locationManager");
	}

	public UserDto connection(String login, String password) {
		User user= userManager.findByLogin(login);
		if(!user.getPassword().equals(password)){
			return null;
		}else{
			return UserConvert.convert(user);
		}
	}

	public void registerUser(UserDto user) {
		User newUser= new User(user.getName(), user.getForname(), user.getLogin(), user.getPassword());
		userManager.save(newUser);
	}

	public void deleteUser(String login) {
		User user= userManager.findByLogin(login);
		userManager.delete(user);
	}

	public void rent(LocationDto location) {
		User user= userManager.findByLogin(location.getRenter());
		Location rent= new Location(user, location.getBookISBN());
		locationManager.save(rent);
	}

	public void returnBook(LocationDto location) {
		User user= userManager.findByLogin(location.getRenter());
		List<Location> locations= locationManager.findByUserId(user.getId());
		for(Location loc: locations){
			if(loc.getBookISBN().equals(location.getBookISBN())){
				loc.setDateReturn(new Date());
				locationManager.save(loc);
				break;
			}
		}
	}

	public List<LocationDto> getListLocation(Integer user_id) {
		List<Location> list= locationManager.findByUserId(user_id);
		return LocationConvert.convertFromListLocationToListDTO(list);
	}

}
